<?php

namespace App\Models\AdminModels;

use App\Models\ParentModel;
use DB;

/**
 * 行业model
 * @author puppet
 */
class Industry extends ParentModel
{
    /**
     * 与模型关联的数据表。
     *
     * @var string
     */
    protected $table = 'pt_industry';

    /**
     * DB::直接操作的数据库表名
     * @var string
     */
    protected $db_table = 'pt_industry';

    /**
     * 主键 默认id。
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 指定是否模型应该被戳记时间。
     *
     * @var bool
     */
    public $timestamps = false;

    public function getAllData()
    {
        return DB::table($this->table)->select('id', 'name')->where('fid', 0)->where('status', 1)->orderBy('sort', 'desc')->get();
    }

    /**
     * 翻页展示所有信息
     */
    public function getPageData($params)
    {
        $res = false;
        $limit_num = (isset($params['limit']) && intval($params['limit']) > 0 && intval($params['limit']) <= 100) ? $params['limit'] : 10;
        $limit_sta = 0;
        $page = 1;
        if (isset($params['page']) && intval($params['page']) > 0) {
            $limit_sta = intval($limit_num * intval($params['page'] - 1));
            $page = intval($params['page']);
        }
        $cou_sql = "SELECT count(*) as count FROM {$this->db_table} WHERE `status` >= ?";
        $sql = "SELECT id,`name`,remark,admin_id,sort,`status`,create_time FROM {$this->db_table} WHERE `status` >= ?";
        $values = [0];
        if (isset($params['name']) && !empty($params['name'])) {
            $cou_sql .= " AND `name` like '%" . $params['name'] . "%'";
            $sql .= " AND `name` like '%" . $params['name'] . "%'";
        }
        $count = DB::select($cou_sql, $values);
        $count = isset($count[0]['count']) ? $count[0]['count'] : 0;
        if (isset($params['order']) && !empty($params['order'])) {
            $order_db = ['id'];
            $sql .= " ORDER BY ";
            foreach ($params['order'] as $order) {
                $result = isset($order_db[$order['column']]) ? $order_db[$order['column']] : '';
                !empty($result) && $sql .= $result . ' ' . $order['dir'] . ',';
            }
            $sql = substr($sql, 0, -1);
        }
        $sql .= " LIMIT $limit_sta,$limit_num";
        $data = DB::select($sql, $values);
        if (!empty($data)) {
            $oAdmin = new Admin();
            foreach ($data as $key => $val) {
                $adminData = $oAdmin->db_get(['admin_id' => ['=', $val['admin_id']]]);
                $val['admin_name'] = !empty($adminData) ? $adminData['admin_name'] : '';
                $data[$key] = $val;
            }
        }
        $res['data'] = $data;
        $res['total'] = $count;
        //总条数记录
        return $res;
    }
}